/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.wall_image.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.solon.service.impl.ServiceImpl;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.UploadedFile;
import org.noear.solon.data.annotation.Cache;
import org.noear.solon.data.annotation.CacheRemove;
import org.noear.solon.data.annotation.Tran;
import vip.xiaonuo.biz.core.enums.BizDataTypeEnum;
import vip.xiaonuo.biz.modular.wall_category.service.BizWallCategoryService;
import vip.xiaonuo.biz.modular.wall_image.entity.BizWallImage;
import vip.xiaonuo.biz.modular.wall_image.mapper.BizWallImageMapper;
import vip.xiaonuo.biz.modular.wall_image.param.BizWallImageAddParam;
import vip.xiaonuo.biz.modular.wall_image.param.BizWallImageEditParam;
import vip.xiaonuo.biz.modular.wall_image.param.BizWallImageIdParam;
import vip.xiaonuo.biz.modular.wall_image.param.BizWallImagePageParam;
import vip.xiaonuo.biz.modular.wall_image.service.BizWallImageService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.listener.CommonDataChangeEventCenter;
import vip.xiaonuo.common.page.CommonPageRequest;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 壁纸信息Service接口实现类
 *
 * @author KingTiger
 * @date 2025/05/27 15:44
 **/
@Component
public class BizWallImageServiceImpl extends ServiceImpl<BizWallImageMapper, BizWallImage> implements BizWallImageService {

    @Inject
    BizWallCategoryService bizWallCategoryService;

    @Override
    public Page<BizWallImage> page(BizWallImagePageParam bizWallImagePageParam) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (ObjectUtil.isNotEmpty(bizWallImagePageParam.getTitle())) {
            queryWrapper.like(BizWallImage::getTitle, bizWallImagePageParam.getTitle());
        }
        if (ObjectUtil.isNotEmpty(bizWallImagePageParam.getTags())) {
            queryWrapper.like(BizWallImage::getTags, bizWallImagePageParam.getTags());
        }
        if (ObjectUtil.isNotEmpty(bizWallImagePageParam.getCategoryId())) {
            queryWrapper.eq(BizWallImage::getCategoryId, bizWallImagePageParam.getCategoryId());
        }
        if (ObjectUtil.isAllNotEmpty(bizWallImagePageParam.getSortField(), bizWallImagePageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizWallImagePageParam.getSortOrder());
            queryWrapper.orderBy(StrUtil.toUnderlineCase(bizWallImagePageParam.getSortField()), bizWallImagePageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()));
        } else {
            queryWrapper.orderBy(BizWallImage::getCreateTime).desc();
        }
        Page<BizWallImage> page = this.page(CommonPageRequest.defaultPage(), queryWrapper);
        if (CollUtil.isNotEmpty(page.getRecords())) {
            page.getRecords().forEach(item -> {
                tranBizWallImage(item);
                item.setUrl(String.format("%s-width200", item.getUrl()));
            });
        }
        return page;
    }

    @Tran
    @Override
    @CacheRemove(tags = "WallCache")
    public void add(BizWallImageAddParam addParam) {
        String description = addParam.getDescription();
        String title = addParam.getTitle();
        if (StrUtil.isBlank(description)) {
            addParam.setDescription(title);
        }
        String tags = addParam.getTags();
        if (StrUtil.isBlank(tags)) {
            addParam.setTags(title);
        }
        BizWallImage bizWallImage = BeanUtil.toBean(addParam, BizWallImage.class);
        this.save(bizWallImage);
        CommonDataChangeEventCenter.doAddWithData(BizDataTypeEnum.WallImage.getValue(), JSONUtil.createArray().put(bizWallImage));
    }

    @Override
    @CacheRemove(tags = "WallCache")
    public void addBatch(String categoryId, UploadedFile file) {
        try {
            List<String> urlList = IoUtil.readUtf8Lines(file.getContent(), new ArrayList<>());
            if (CollUtil.isEmpty(urlList)) {
                throw new CommonException("请上传正确的壁纸图片URL");
            }
            urlList = urlList.stream().filter(url -> StrUtil.isNotBlank(url)).collect(Collectors.toList());
            urlList = urlList.stream().filter(url -> url.startsWith("http")).collect(Collectors.toList());
            if (CollUtil.isEmpty(urlList)) {
                throw new CommonException("请上传正确的壁纸图片URL");
            }
            //
            AtomicInteger index = new AtomicInteger(1);

            // 假设每一行为一个图片URL，将其批量保存为壁纸信息
            List<BizWallImage> wallImages = urlList.stream().map(url -> {
                BizWallImage wallImage = new BizWallImage();
                wallImage.setCategoryId(categoryId);
                wallImage.setUrl(url);
                wallImage.setTitle(String.valueOf(index.get()));
                wallImage.setDescription(DateUtil.formatDateTime(new Date()));
                wallImage.setTags(DateUtil.formatDateTime(new Date()));
                index.getAndIncrement();
                return wallImage;
            }).collect(Collectors.toList());

            this.saveBatch(wallImages);
            CommonDataChangeEventCenter.doAddWithData(BizDataTypeEnum.WallImage.getValue(), JSONUtil.parseArray(wallImages));
        } catch (Exception e) {
            throw new CommonException("批量导入壁纸失败：{}", e.getMessage());
        }
    }

    @Tran
    @Override
    @CacheRemove(tags = "WallCache")
    public void edit(BizWallImageEditParam editParam) {
        String description = editParam.getDescription();
        String title = editParam.getTitle();
        if (StrUtil.isBlank(description)) {
            editParam.setDescription(title);
        }
        String tags = editParam.getTags();
        if (StrUtil.isBlank(tags)) {
            editParam.setTags(title);
        }
        BizWallImage bizWallImage = this.queryEntity(editParam.getId());
        BeanUtil.copyProperties(editParam, bizWallImage);
        this.updateById(bizWallImage);
        CommonDataChangeEventCenter.doUpdateWithData(BizDataTypeEnum.WallImage.getValue(), JSONUtil.createArray().put(bizWallImage));
    }

    @Tran
    @Override
    @CacheRemove(tags = "WallCache")
    public void delete(List<BizWallImageIdParam> bizWallImageIdParamList) {
        // 执行删除
        List<String> idList = CollStreamUtil.toList(bizWallImageIdParamList, BizWallImageIdParam::getId);
        this.removeByIds(idList);
        CommonDataChangeEventCenter.doDeleteWithDataId(BizDataTypeEnum.WallImage.getValue(), idList);
    }

    @Override
    public BizWallImage detail(BizWallImageIdParam bizWallImageIdParam) {
        BizWallImage bizWallImage = this.queryEntity(bizWallImageIdParam.getId());
        if (ObjectUtil.isNotNull(bizWallImage)) {
            tranBizWallImage(bizWallImage);
        }
        return bizWallImage;
    }

    @Override
    public BizWallImage queryEntity(String id) {
        BizWallImage bizWallImage = this.getById(id);
        if (ObjectUtil.isEmpty(bizWallImage)) {
            throw new CommonException("壁纸信息不存在，id值为：{}", id);
        }
        tranBizWallImage(bizWallImage);
        return bizWallImage;
    }

    @Override
    public void tranBizWallImage(BizWallImage bizWallImage) {
        if (Objects.isNull(bizWallImage)) {
            return;
        }
        bizWallImage.setCategoryName(bizWallCategoryService.getNameById(bizWallImage.getCategoryId()));
    }

    @Cache(key = "WallCache::Wall::Image::getUrlById::${id}", service = "CacheRedis", tags = "WallCache", seconds = 86400)
    @Override
    public String getUrlById(String id) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.select(BizWallImage::getUrl);
        queryWrapper.eq(BizWallImage::getId, id);
        BizWallImage bizWallImage = mapper.selectOneByQuery(queryWrapper);
        if (Objects.isNull(bizWallImage)) {
            return null;
        }
        return bizWallImage.getUrl();
    }
}
